package com.lyw.gulimall.product.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lyw.common.constant.ProductConstant;
import com.lyw.common.response.ObjectRestResponse;
import com.lyw.common.to.SkuReductionTo;
import com.lyw.common.to.SpuBoundTo;
import com.lyw.common.utils.R;
import com.lyw.gulimall.product.entity.*;
import com.lyw.gulimall.product.feign.CouponFeignService;
import com.lyw.gulimall.product.feign.SearchFeignService;
import com.lyw.gulimall.product.feign.WareFeighServic;
import com.lyw.gulimall.product.service.*;
import com.lyw.common.to.SkuEsModel;
import com.lyw.gulimall.product.vo.SkuHasStockVo;
import com.lyw.gulimall.product.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lyw.common.utils.PageUtils;
import com.lyw.common.utils.Query;

import com.lyw.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

@Slf4j
@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private WareFeighServic wareFeighServic;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }


    @Override
    @Transactional
    public void saveSpuInfo(SpuSaveVo vo) {

        // 1.保存spu的基本信息 pms_sku_info
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());

        this.saveBaseSpuInfo(infoEntity);

        // 2.保存spu的商品描述 pms_spu_info_desc
        // 商品描述
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        descEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(descEntity);

        // 3.保存spu的图片集  pms_spu_images
        List<String> images = vo.getImages();
        spuImagesService.saveImages(infoEntity.getId(), images);

        // 4.保存spu的规格参数； pms_product_attr_value
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> valueEntityList = baseAttrs.stream().map(attrValue -> {
            ProductAttrValueEntity attrValueEntity = new ProductAttrValueEntity();
            attrValueEntity.setAttrId(attrValue.getAttrId());
            AttrEntity attrEntity = attrService.getById(attrValue.getAttrId());
            attrValueEntity.setAttrName(attrEntity.getAttrName());
            attrValueEntity.setAttrValue(attrValue.getAttrValues());
            attrValueEntity.setSpuId(infoEntity.getId());
            attrValueEntity.setQuickShow(attrValue.getShowDesc());

            return attrValueEntity;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(valueEntityList);

        // 5.保存spu的积分信息；gulimall_sms -》sms_spu_bounds
        Bounds bounds = vo.getBounds();
        SpuBoundTo boundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, boundTo);
        boundTo.setSpuId(infoEntity.getId());

        R r = couponFeignService.saveSpuBounds(boundTo);

        if (r.getCode() != 0) {
            log.info("远程保存 SKU 积分信息失败");
        }

        // 6.保存spu对应的sku商品信息
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            skus.forEach(sku -> {
                String defaultImg = "";

                for (Images image : sku.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku, skuInfoEntity);
                skuInfoEntity.setBrandId(infoEntity.getBrandId());
                skuInfoEntity.setCatalogId(infoEntity.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSpuId(infoEntity.getId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                // 6.1、sku的基本信息；pms_sku_info
                skuInfoService.saveSkuInfo(skuInfoEntity);

                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> skuImageEntities = sku.getImages().stream().map(image -> {
                    SkuImagesEntity skuImage = new SkuImagesEntity();

                    skuImage.setSkuId(skuId);
                    skuImage.setImgUrl(image.getImgUrl());
                    skuImage.setDefaultImg(image.getDefaultImg());

                    return skuImage;
                // 过滤掉 没有图片路径的无需保存 url 为空的数据
                }).filter(entity -> !StringUtils.isEmpty(entity.getImgUrl())).collect(Collectors.toList());
                // 6.2、sku的图片信息；pms_spu_images
                skuImagesService.saveImageInfo(skuImageEntities);

                List<Attr> attrs = sku.getAttr();
                List<SkuSaleAttrValueEntity> skuAttrEntities = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuAttrEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr, skuAttrEntity);

                    skuAttrEntity.setSkuId(skuId);

                    return skuAttrEntity;
                }).collect(Collectors.toList());
                // 6.3、sku的销售属性信息；pms_sku_sale_attr_value
                skuSaleAttrValueService.saveBatch(skuAttrEntities);

                // A 服务将数据封装成对象以 JSON 的形式传送给 B 服务，这个对象被称为 TO Transfer Object
                // sku的优惠、满减信息 gulimall_sms -》 sms_sku_ladder/满减表 sms_sku_full_reduction/会员价格表 sms_member_price/商品积分表 sms_spu_bounds
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(sku, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                // 去掉无用的数据
                // 有可能没有打折有满减优惠
                // FullCount 是满多少件打折 FullPrice 是满多少钱优惠
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 0) {
                        log.info("远程保存 SKU 满减信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity infoEntity) {
        baseMapper.insert(infoEntity);
    }

    @Override
    public IPage<Map<String, Object>> queryPageByCondition(Integer page, Integer limit, String sidx, String order, String key, Long catelogId, Long brandId, String status) {
        Page<Map<String, Object>> result = new Page<>(page, limit);
        QueryWrapper<SpuInfoEntity> lqw = new QueryWrapper<SpuInfoEntity>();

        if (!StringUtils.isEmpty(key)) {
            lqw.and(wrapper -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        if (!StringUtils.isEmpty(status)) {
            lqw.eq("publish_status", status);
        }

        if (!StringUtils.isEmpty(brandId) && brandId > 0) {
            lqw.eq("brand_id", brandId);
        }

        if (!StringUtils.isEmpty(catelogId) && catelogId > 0) {
            lqw.eq("catalog_id", catelogId);
        }

        if (!StringUtils.isEmpty(order)) {
            if (order.equalsIgnoreCase("asc")) {
                if (!StringUtils.isEmpty(sidx)) {
                    lqw.orderByAsc(sidx);
                } else {
                  lqw.orderByAsc("id");
                }
            } else {
                if (!StringUtils.isEmpty(sidx)) {
                    lqw.orderByDesc(sidx);
                } else {
                    lqw.orderByDesc("id");
                }
            }
        }

        IPage<Map<String, Object>> list = baseMapper.selectPageList(result, lqw);
        return list;
    }

    /**
     * 商品上架功能
     * @param spuId
     */
    @Override
    @Transactional
    public void up(Long spuId) {
        // 1、查出 spuid 对应的所有 sku 信息，品牌的名字
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.getSkusBySpuId(spuId);

        // TODO 4、查询当前 sku 的所有可以被检索的的规格属性 attrId,attrName,attrValue 只需要查一遍
        List<Long> attrIds= productAttrValueService.getSpuAttrIds(spuId);
        List<AttrEntity> searchAttrEntities = attrService.selectSearchAttrIds(attrIds);
        List<SkuEsModel.Attrs> attrsList = searchAttrEntities.stream().map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            attrs.setAttrId(item.getAttrId());
            attrs.setAttrName(item.getAttrName());
            attrs.setAttrValue(item.getValueSelect());
            return attrs;
        }).collect(Collectors.toList());


        // TODO 1、发送远程服务，查询是否有库存
        List<Long> skuIds = skuInfoEntities.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        Map<Long, Integer> stockMap = null;

        try {
            ObjectRestResponse<List<SkuHasStockVo>> tos = wareFeighServic.getSkuHasStock(skuIds);
            stockMap = tos.getData().stream().collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getStock()));
        } catch (Exception e) {
            log.error(LocalDateTime.now().toString() + ": >>>>>>>>>>>>>>>>>>>>> 库存服务查询异常,原因：{}", e);
        }

        // 所有的上架商品
        // 2、封装 sku 的信息
        Map<Long, Integer> finalStockMap = stockMap;
        List<SkuEsModel> skuEsModels = skuInfoEntities.stream().map(sku -> {
            // 组装需要的数据
            SkuEsModel esModel = new SkuEsModel();
            BeanUtils.copyProperties(sku, esModel);
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            // 设置是否有库存
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku) != null && finalStockMap.get(sku) > 0);
            }

            // TODO 2、热度评分。刚上架的 0
            esModel.setHotScore(0L);

            // TODO 3、查出品牌名字分类名字信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());

            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogName(categoryEntity.getName());

            // 设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        // TODO 5、将数据发送给 ES 保存：gulimall-search
        R result = searchFeignService.productStatusUp(skuEsModels);
        if (result.getCode() == 0) {
            // TODO 6、修改当前 spu 的状态信息为已发布
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        } else {
            // TODO 7、重复调用？接口幂等性
            // Feign 的调用流程
            /**T
             * 1、Feign 在远程调用的时候会判断是不是 equals、hashCode、toString 方法
             * 2、dispatch.get(method).invoke(args) 通过这个代码真正调用
             * 3、在这个子类中处理 SynchronousMethodHandler 将数据封装到这个模板中 RequestTemplate template = buildTemplateFromArgs.create(argv);
             * 4、构建重试器 Retryer retryer = this.retryer.clone();
             * 5、发送请求执行（执行成功后会解码） return executeAndDecode(template, options);
             * 6、如果发送请求的过程中出现了异常，继续重试 retryer.continueOrPropagate(e);
                 try {
                    retryer.continueOrPropagate(e);
                 } catch (RetryableException th) {
                    Throwable cause = th.getCause();
                    if (propagationPolicy == UNWRAP && cause != null) {
                        throw cause;
                    } else {
                        throw th;
                    }
                 }
                // 记录重试日志
                if (logLevel != Logger.Level.NONE) {
                    logger.logRetry(metadata.configKey(), logLevel);
                }

             */
        }
    }
}